<template>
  <!--查看单个订单弹框中的订单商品列表组件  -->
  <div class="atable-box" :id="tableId" ref="table_box">
    <!-- {{tableHeader}} {{eleHeader}} -->
    <a-table
      :size="size"
      :columns="setColumns"
      :data-source="tableData"
      :pagination="pagination"
      :row-selection="selectionOpt"
      :loading="loading"
      tableLayout="fixed"
      :expandRowByClick="true"
      :key="tableKey"
      :defaultExpandAllRows="isExpandAllRows"
      @change="handleTableChange"
      @expand="expand"
      :scroll="{y:scroll.y-tableHeader-tableTitle-tablePage}"
      :customHeaderRow="customHeaderRow"
      :customRow="customRow"
      :rowClassName="setClassName"
    >
      <!-- 子表格插槽 -->
      <!-- <template :slot="haveChild?'expandedRowRender" slot-scope="">
        <slot name="innerTable"></slot>
      </template>-->

      <!-- <slot name="innerTable" slot-scope="record" :record="record" ></slot> -->
      <div v-if="haveChild" :slot="haveChild?'expandedRowRender':''" slot-scope="record" >
        <a-list-table
          :tableId="'id'+record.pid"
          :columns="innerTable.innerColumns"
          :tableData="record.child"
          :isSelecttion="isInnerSelecttion"
          @onselectChange="(selectedRowKeys, selectedRows)=>onselectChange(selectedRowKeys, selectedRows,record)"
          size="small"
          :pagination="false"
          :loading="innerTable.innerLoading"
          :inputNameObj="innerTable.innerInputName"
          @onAction="onInnerAction"
          @onBlur="onInnerBlur"
          @onChangeInput="onInnerChangeInput"
        >
        </a-list-table>
      </div>
      <template slot="title" >
        <div class="setHeader" ref="setHeader" v-show="isSetHeader">
          <span style="white-space:nowrap">显示配置：</span>
          <a-checkbox style="white-space:nowrap" :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange">
            全部
          </a-checkbox>
          <a-checkbox-group v-model="checkedList" :options="plainOptions" @change="onCheckedList"/>
        </div>
      </template>
      <template slot="column" slot-scope="text, record, index">
        <a @click="onTouchCell($event, text, record,index)">{{ text }}</a>
      </template>
      <template 
        v-for="link in links"
        :slot="link" 
        slot-scope="text, record, index">
        <div :key="link">
          <a @click.stop="onTouchlinkCell($event, text, record, index,link)">{{ text }}</a>
        </div>
      </template>
      <template slot="isReceive" slot-scope="text, record,index">
        <div @click.stop>
          <!-- <a-switch 
          checked-children="是" 
          un-checked-children="否" 
          
          @change="checked => handleSwitchChange(checked, record.key,'isReceive',index,record)"  /> -->
          <a-radio-group 
            :default-value="appState.deliveryState.received.code" 
            @change="e => handleSwitchChange( e.target.value, record.key,'isReceive',index,record)"
            button-style="solid">
            <a-radio :value="appState.deliveryState.rejected.code">
              拒收
            </a-radio>
            <a-radio :value="appState.deliveryState.received.code">
              收货
            </a-radio>
          </a-radio-group>
        </div>
        
      </template>
      <template slot="action" slot-scope="text, record,index">
         <template>
          <a-tag style="margin: 2px;" v-for="(item, ind) in text" :key="ind" class="actionBtn" color='#eee' >
            <a :name="'#'+item+record.pid" @click.stop="onAction($event, item, record, index)">
              <a-tooltip placement="topLeft" :title="item.indexOf(record.btnKeys)>=0?record.btnTips:''">
                {{ item }}
              </a-tooltip>
            </a>
          </a-tag>
          
          
           <!-- <span v-for="(item, ind) in text" :key="ind">
             <a style="margin: 2px"   @click="onAction($event, item, record, index)">{{item}}</a>
            <a-divider   type="vertical" />
           </span> -->
         </template>
      </template> 
      <template slot="img" slot-scope="text">
        <viewer class="viewer" :options="options">
          <img class="imgs" 
            :src="imgbaseurl+text"  
            :data-src="imgbaseurl + text">
        </viewer>
      </template>
      <template slot="unfilled" slot-scope="text">
        <span v-if="text">{{text}}</span>
        <span v-else style="color:#fab600">未填写</span>
      </template>
      <template slot="tofixed2" slot-scope="text">
        <span>{{tofixed2(text)}}</span>
      </template>
      <template slot="percentage" slot-scope="text">
        <span>{{text?text+'%':null}}</span>
      </template>
      <template slot="approvalNum" slot-scope="text, record, index">
        
        <span v-if="record.approvalLicense=='1'">
          <a @click="onTouchTagCell($event, text, record, index,'approvalNum')" style="fontSize:16px;">
            <a-icon theme="twoTone" two-tone-color="#52c41a" type="api" />
          </a>
          {{text}}
        </span>
        <span v-else>
          <a @click="onTouchTagCell($event, text, record, index,'approvalNum')" style="fontSize:16px;">
            <a-icon theme="twoTone" two-tone-color="#E02E24" type="api" />
          </a>
          未填写
        </span>
        
      </template>
      <template 
        v-for="stateField in renderStateByField"
        :slot="stateField" 
        slot-scope="text, record, index">
        <div :key="stateField">
          <a-tag style="text-align: center;font-size: 9px;" :color="renderState(text, record, index,stateField)[1]" >{{renderState(text, record, index,stateField)[0]}}</a-tag>
        </div>
      </template>
      <template 
        v-for="tag in tagClicks"
        :slot="tag" 
        slot-scope="text, record, index">
        <div :key="tag">
          <a @click="onTouchTagCell($event, text, record, index,tag)">
            <a-tag style="width:50px;text-align: center;font-size: 8px;" v-if="text === '1'" color="green">查看</a-tag>
            <a-tag style="width:50px;text-align: center;font-size: 8px;" v-else color="purple">未上传</a-tag>
          </a>
        </div>
      </template>
      <template 
        v-for="tag2 in tagClicks2"
        :slot="tag2" 
        slot-scope="text, record, index">
        <div :key="tag2">
          <span v-if="text">
            <a style="whiteSpace:nowrap;color:green;fontSize:16px;margin:0 3px" @click="onTouchTagCell($event, text, record, index,tag2)" v-if="record.manufacturerLicense=='1'" > <a-icon  theme="twoTone" two-tone-color="#52c41a" type="idcard" /></a>
            <a style="whiteSpace:nowrap;color:red;fontSize:16px;margin:0 3px" @click="onTouchTagCell($event, text, record, index,tag2)" v-else><a-icon style=""  theme="twoTone" two-tone-color="#E02E24" type="idcard" /></a>
            {{text}}
          </span>
          <span v-else>
            未添加
            <!-- <a style="whiteSpace:nowrap;color:red;fontSize:16px;margin:0 3px" @click="onTouchTagCell($event, text, record, index,tag)" ><a-icon style=""  theme="filled" type="plus-circle" /></a> -->
            <a-tag style="width:50px;text-align: center;font-size: 8px;"  color="blue">添加</a-tag>
          </span>
        </div>
      </template>
      <template 
        v-for="tag3 in tagClicks3"
        :slot="tag3" 
        slot-scope="text, record, index">
        <div :key="tag3">
          <a @click="onTouchTagCell($event, text, record, index,tag3)">
            <a-tag style="width:50px;text-align: center;font-size: 8px;" v-if="text" color="green">查看</a-tag>
            <a-tag style="width:50px;text-align: center;font-size: 8px;" v-else color="purple">未上传</a-tag>
          </a>
        </div>
      </template>
      <template
        v-for="col in inputName"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <a-input
            v-if="!record.noInput"
            style="margin: -5px 0"
            :value="text"
            :min="1"
            placeholder="请输入"
            :ref="col"
            @change="e => handleChange(e,e.target.value, record.key,col,index)"
            @blur="onBlur($event, text, record, index,col)"
          />
          <span v-else>{{text}}</span>
        </div>
      </template>
      <template
        v-for="colobj in inputNameObj"
        :slot="colobj.name"
        slot-scope="text, record, index"
      >
        <div :key="colobj.name" class="inputNameObj" style="display:flex">
          <span style="margin:0 3px;color:red;fontSize:16px">*</span>
          <span v-if="!colobj.type">{{text}}</span>
          <!-- 生产日期 -->
          <a-date-picker
            v-if="colobj.type=='productDate'"
            :value="text"
            :disabled="record.disabled"
            :disabled-date="disabledAfterDate"
            :placeholder="colobj.placeholder"
            @change="(date,dateString)=>onDateChange(date,dateString,record,colobj.name,index)"
            />
          <!-- 有效期 -->
          <a-date-picker
            v-if="colobj.type=='expiryDate'"
            :value="text"
            :disabled="record.disabled"
            :disabled-date="disabledBeforeDate"
            :placeholder="colobj.placeholder"
            @change="(date,dateString)=>onDateChange(date,dateString,record,colobj.name,index)"
            />
          <a-input
            v-if="colobj.type=='number'"
            style="margin: -5px 0"
            :value="text?parseInt(text):null"
            type="number"
            :min="1"
            :placeholder="colobj.placeholder"
            :ref="colobj.name"
            @change="e => handleChange(e,e.target.value, record.key, colobj.name,index,record)"
            @blur="onBlur($event, text, record, index,colobj.name)"
          />
          <a-input
            v-if="colobj.type=='text'"
            style="margin: -5px 0"
            :value="text"
            type="text"
            :disabled="record.disabled"
            :placeholder="colobj.placeholder"
            :ref="colobj.name"
            :id="colobj.name+'-'+record.key"
            @change="e => handleChange(e,e.target.value, record.key, colobj.name,index,record)"
            @blur="onBlur($event, text, record, index,colobj.name)"
          />
          
        </div>
      </template>
      <template
        v-for="autoItem in autoComputed"
        :slot="autoItem"
        slot-scope="text, record, index"
      >
        <div :key="autoItem">
          <span v-if="autoItem=='execNum'">{{computeExecNum(text, record, index,'execNum','execNum')}}</span>
          <span v-if="autoItem=='totalPrice'">￥{{computeTotalPrice(text, record, index,'totalPrice','execNum','iunitprice')}}</span>

          <span v-if="autoItem=='num'">{{computeExecNum(text, record, index,autoItem,'num','num')}}</span>
          <span v-if="autoItem=='totalPrices'">￥{{computeTotalPrice(text, record, index,'totalPrice','num','iunitprice')}}</span>
          <!-- <span v-else>{{text}}</span> -->
        </div>
      </template>
    </a-table>
  </div>
</template>

<script>
import baseapi from '@/api/base'
import moment from 'moment'
export default {
  name:'aListTable',
  components:{
  },
  props: {
    size:{
      type:String,
      default:'middle'
    },
    columns: {
      type: Array,
    },
    //表头显示是否可配置
    // isSetHeader:{
    //   type:Boolean,
    //   default:true
    // },
    //接收渲染tag点击的字段数组
    tagClicks:{
      type: Array,
    },
    //接收渲染tag点击的字段数组
    tagClicks2:{
      type: Array,
    },
    //接收渲染tag点击的字段数组
    tagClicks3:{
      type: Array,
    },
    //接收渲染input框的字段数组
    inputName:{
      type: Array,
    },
    //接收渲染多类型input框的字段数组
    inputNameObj:{
      type: Array,
    },
    //接收渲染成链接字段数组
    links:{
      type: Array,
    },
    //接收通过状态表渲染状态字段数组，注意，数组中的字段应stateTable中的状态对象名对应
    renderStateByField:{
      type: Array,
    },
    //接收渲染自动计算的字段数组
    autoComputed:{
      type: Array,
    },
    tableData: {
      type: Array,
    },
    pagination: {
      type: Object|Boolean,
    },
    isSelecttion: {
      type: Boolean,
      default: false,
    },
    haveChild:{
      type:Boolean,
      default:false
    },
    //是否展开所有的子表格
    isExpandAllRows:{
      type:Boolean,
      default:true
    },
    innerTable:{
      type:Object,
    },
    isInnerSelecttion:{
      type:Boolean,
      default:false
    },
    loading:{
        type:Boolean
    },
    scroll:{
      type:Object,
      default:()=>{return {  y: false }}
    },
    //如果一个页面上又多个table时，需给每个table设置不同的tableId
    tableId:{
      type:String,
      default:'atable'
    },
    //如果一个页面上又多个table时，布局发生改变时
    changeLayout:{
      type:Boolean,
      default:false
    }
  },
  data() {
    return {
      isSetHeader:false,
      //全部columns
      plainOptions:[],
      //选择显示的columns
      checkedList:[],
      // 是否半选  true:半选，false:全选
      indeterminate: false,
      //是否全选
      checkAll: true, 
      scrollY:'',
      scrolls:{  y: 290 },
      tableHeader:79,
      tableTitle:30,
      tablePage:41,
      imgbaseurl: baseapi.imgShowUrl,
      options: {
        url: 'data-src'
      },
      selecteds:[],
      touchRowKey:null,
      isChange:false,
      eleHeader:'#'+this.tableId+' .ant-table-header',
      eleTitle:'#'+this.tableId+' .ant-table-title',
      tableKey:'t12',
      el:null,
      //表格行内input的值发生改变
      handleChangeVal:null,
    }
  },
  watch:{
    tableData: {
        handler(val, oldVal) {
          console.log('this.handleChangeVal');
          this.selecteds=[] //该语句会导致表格数据发生变化时取消选择
          // this.tableKey='123'//该语句会导致子表格第一次输入时失去焦点
          //数据发生变化时重新设置TableHeader
          this.setTableHeader()
        },
        deep: true,
        // immediate:true
    },
    columns:{
      handler(val,oldVal){
        if (this.columns.length) {
          let viewColumns = []
          let checkedColumns=[]
          for (const item of this.columns) {
            viewColumns.push(item.title)
            if (!item.hidden) {
              checkedColumns.push(item.title)
            }
          }
          this.indeterminate=(checkedColumns.length==viewColumns.length)?false:true
          this.checkedList=checkedColumns
          this.plainOptions=viewColumns
          return viewColumns
        }else{
          this.checkedList=[]
          this.plainOptions=[]
          return []
        }
      },
      deep: true,
      immediate:true
    },
    handleChangeVal(val){
    },
    //如果一个页面上有多个table时，布局发生改变时
    changeLayout(val){
      this.setTableHeader()
    },
    '$store.state.screenWidth':function(val){ //监听屏幕宽度变化
      // console.log('监听屏幕宽度变化');
      this.setTableHeader()
    },
    '$store.state.screenHeight':function(val){ //监听屏幕高度变化
      this.setTableHeader()
    },
  },
  mounted(){
    setTimeout(()=>{
      this.tableKey='1234'
    },200)
    //初始化TableHeader
    this.setTableHeader()
  },
  computed: {
    setColumns(){
        let setCol={
          title: '',
          dataIndex: 'setCol',
          key: 'setCol',
          width:7,
          filterDropdown: true,
          filterIcon: ()=>{
            return(
              <a-tooltip placement="topRight">
                <template slot="title">
                  <span>筛选表头显示</span>
                </template>
                <div class="titleConfig" onClick={ ()=>this.onTouchFilter()} >
                   <a-icon type="funnel-plot" theme="twoTone" style="fontSize:13px"  />
                </div>
              </a-tooltip>
              
            )
          },
        }
      if (this.checkedList.length) {
        let viewColumns =this.columns.filter(item => this.checkedList.indexOf(item.title) > -1)
        viewColumns.push(setCol)
        this.$nextTick(()=>{
          this.setTableHeader()
        })
        return viewColumns
      }else{
        return [setCol]
      }
    },
    renderState(){
      return (text, record, index,stateField)=>{
        let state= this.findState(text,null,stateField)
        if (state!=-1) {
          return  [state.value,state.color]
        }else{
          return [text+'(-1)','blue']
        }
      }
    },
    selectionOpt() {
      if (this.isSelecttion) {
        return {
          //多选操作 
          selectedRowKeys:this.selecteds,
          onChange: (selectedRowKeys, selectedRows)=>{
            this.selecteds=selectedRowKeys
            console.log("多选操作onChange",`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
            this.$emit("onselectChange",selectedRowKeys, selectedRows)
          },
          onSelect: (record, selected, selectedRows) => {
            // console.log("多选操作onSelect",record, selected, selectedRows)
            this.$emit("onSelect",record, selected, selectedRows)
          },
          onSelectAll: (selected, selectedRows, changeRows) => {
            // console.log("多选操作onSelectAll",selected, selectedRows, changeRows)
            this.$emit("onSelectAll",selected, selectedRows, changeRows)
          },
        }
      } else {
        return undefined
      }
    },
    tofixed2(){
      return (text)=>{
        if (text) {
          let toNum=parseFloat(text)
          return toNum.toFixed(2)
        }else{
          return ''
        }
      }
    },
    computeExecNum(){
      return (text, record, index,resField,depField1)=>{
        if(record.child.length){
          let res=0
          for (let item of record.child) {
            let data1= item[depField1]?parseInt(item[depField1]):0
            res+=data1
          }
          record[resField]=res
          return res
        }else{
          // record[resField]=0
          const newData = [...this.tableData];
          this.tableData.splice(index,1)
          return 0
        }
      }
    },
    computeTotalPrice(){
      return (text, record, index,resField,depField1,depField2)=>{
        if(record.child.length){
          let res=0
          let totalP=0
          let data2= parseFloat(record[depField2])
          for (let item of record.child) {
            let data1= item[depField1]?parseInt(item[depField1]):0
            res+=data1
          }
          totalP=res*data2
          let final=Math.round(totalP * 100) / 100
          record[resField]=final
          return final.toFixed(2)
        }else{
          record[resField]=0.00
          return 0.00
        }
      }
    }
  },
  methods: {
    //控制整个表格title是否显示
    onTouchFilter(){
      this.isSetHeader=!this.isSetHeader
      this.setTableHeader()
    },
    setTableHeader(){
      let tableHeader=document.querySelector(this.eleHeader)
      let tableTitle=document.querySelector(this.eleTitle)
      this.$nextTick(()=>{
        this.tableHeader=tableHeader.offsetHeight
        this.tableTitle=tableTitle.offsetHeight
        console.log(this.tableHeader,this.tableTitle);
      })
    },
    onCheckedList(checkedList){
      this.indeterminate = !!checkedList.length && checkedList.length < this.plainOptions.length;
      this.checkAll = checkedList.length === this.plainOptions.length;
    },
    onCheckAllChange(e) {
      Object.assign(this, {
        checkedList: e.target.checked ? this.plainOptions : [],
        indeterminate: false,
        checkAll: e.target.checked,
      });
    },
    
    disabledBeforeDate(current) {
      // Can not select days before today and today
      return current && current < moment().endOf('day');
    },
    disabledAfterDate(current) {
      // Can not select days before today and today
      return current && current > moment().endOf('day');
    },
    handleTableChange(pagination, filters, sorter) {
      console.log('触发改变页码,筛选,排序时的回调', pagination)
      this.$emit("onTableChange",pagination, filters, sorter)
    },
    expand(expanded, record){
      this.$emit("expand",expanded, record)
    },
    onTouchCell(event, text, record, index) {
      console.log('点击单元格中的内容',  text, record, index)
      this.$emit("onTouchCell",text, record, index)
    },
    onTouchlinkCell(event, text, record, index,link){
      console.log('点击单元格中link的内容',text, record, index,link)
      this.$emit("onTouchlinkCell",text, record, index,link)
    },
    onTouchTagCell(event, text, record, index,col){
      console.log('点击单元格中tag的内容',text, record, index,col)
      this.$emit("onTouchTagCell",text, record, index,col)
    },
    onAction(event, text, record, index) {
      console.log('点击list中的操作按钮', event, text, record, index)
      this.$emit("onAction",text, record, index)
      // this.$emit("clearSelect",record)
    },
    onInnerAction(text, record, index){
      this.$emit("onInnerAction",text, record, index)
      // this.$emit("clearSelect",record)
    },  
    handleSwitchChange(value, key, column,index,record){
      console.log(value, key, column,index,record);
      const newData = [...this.tableData];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        this.isChange=true
        target[column] = value;
        this.$emit('onChangeSwitch',target,value,key,column,index)
      }
    },                 
    handleChange(e,value, key, column,index,record) {
      console.log(value, key, column,index,record);
      if (column=='num'||column=='execNum') {
        value=value?value:1
      }else{
        value=value?value:null
      }
      const newData = [...this.tableData];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        this.isChange=true
        target[column] = value;
        this.$emit('onChangeInput',target,value,key,column,index)
      }
    },
    onInnerChangeInput(target,value,key,column,index){
      console.log(target,value,key,column,index);
      this.$emit("onInnerChangeInput",target,value,key,column,index)
    },
    onBlur(event,text, record, index,col) {
      console.log(text, record, index,col);
      //失去焦点时值是否改变
      if (this.isChange) {
        this.$emit('onBlur',text, record, index,col)
        this.isChange=false
      }
      
    },
    onInnerBlur(text, record, index,col){
      this.$emit("onInnerBlur",text, record, index,col)
      this.$emit("clearSelect",record)
    },
    onselectChange(selectedRowKeys, selectedRows,record){
      console.log(selectedRowKeys, selectedRows,record);
      this.$emit("onInnerSelect",selectedRowKeys, selectedRows,record)
    },
    // 时间变化
    onDateChange(date,dateString,record,col,index) {
      console.log(date,dateString,record,col,index);
      record[col]=dateString
      this.$emit('onBlur',dateString, record, index,col)
      
    },
    customHeaderRow(column){
      return{
        style: {
          // 行背景色
          "background-color": "#eee",
        },
        // on: {
        //   click: (e) => {// 点击表头行
        //     console.log(e,column);
        //   },        
        // }

      }
    },
    customRow(record, index) {
      return {
        // // 这个style就是我自定义的属性，也就是官方文档中的props
        // style: {
        //   // 字体颜色
        //   color: record.style ? record.style.fontColor : "rgba(0, 0, 0, 0.65)",
        //   // 行背景色
        //   "background-color": record.style ? record.style.bgColor : "#ffffff",
        //   // 字体类型
        //   "font-family": record.style ? record.style.fontType : "Microsoft YaHei",
        //   // 下划线
        //   "text-decoration":
        //   record.style && record.style.underline ? "underline" : "unset",
        //   // 字体样式-斜体
        //   "font-style": record.style && record.style.italics ? "italic" : "unset",
        //   // 字体样式-斜体
        //   "font-weight": record.style && record.style.bold ? "bolder" : "unset",
        // },
        on: {
          // 鼠标单击行
          click: event => {
            // record.style.bgColor='rgb(230 247 255)'
            this.touchRowKey=record.key
            this.$emit('onTouchRow',record, index)
            this.setTableHeader()
          },
        },
      }
    },
    setClassName(record, index){
      return record.key === this.touchRowKey ? 'clickStyle' : ''
    },


  },
}
</script>

<style lang="less">
.ant-table-title{
  padding: 0 !important;
}
.titleConfig{
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.setHeader{
  width: 100%;
  min-height: 30px;
  display: flex;
  align-items: center;
}
.ctrl{
  width: 20px;
  text-align: center;
}
.optView{
  flex: 1;
}
.clickStyle{
  background-color: rgb(230 247 255);
}
.atable-box{
  width: 100%;
}
.ant-table td { 
  text-align: justify;
  text-justify: newspaper;
  word-break: break-all;
}
.imgs{
  max-width: 120px;
  max-height: 120px;
}
.imgs:hover{
  cursor: pointer;
}
.ant-table-pagination.ant-pagination{
  margin: 0;
  margin-top: 4px;
  margin-bottom: 2px;
  height: 38px;
  overflow: scroll;
}
.actionBtn{
  background-color: @primary-color !important;
}
</style>

columns =  [
    { 
      title: '表头标题',
      dataIndex: '字段名(与tableData字段一致)',
      key: '字段标识(不能重复，建议与字段名一样)', 
      align: 'center',//表格内容位置
      scopedSlots: { customRender: 'slotName' }},用于修改表格内容显示的插槽名字
      hidden:false,//是否显示该列
      width:180,//列宽
  
    { title: '操作', dataIndex: 'action', key: 'operation',hidden:true,  width: 70, align: 'center', scopedSlots: { customRender: 'action' }},
  ]